package com.example.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.constants.BehaviorConstants;
import com.example.common.redis.CacheService;
import com.example.common.util.R;
import com.example.common.util.ResultCodeRecord;
import com.example.model.user.dto.UserRelationDto;
import com.example.model.user.pojo.User;
import com.example.model.user.pojo.UserFollow;
import com.example.user.mapper.UserFollowMapper;
import com.example.user.service.UserFollowService;
import com.example.utils.thread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserFollowServiceImpl extends ServiceImpl< UserFollowMapper, UserFollow > implements UserFollowService {
    @Autowired
    private CacheService cacheService;

    @Override
    public boolean userFollow(UserRelationDto userRelationDto) {
        // 1、参数校验
        if (userRelationDto.getOperation() == null || userRelationDto.getOperation() < 0 || userRelationDto.getOperation() > 1) {
            return R.error(ResultCodeRecord.PARAM_INVALID).isFlag();
        }
        // 2、判断是否登录
        User user = UserThreadLocal.getUser();
        if (user == null) {
            return R.error(ResultCodeRecord.NEED_LOGIN).isFlag();
        }
        Integer userId = user.getUserId();
        // 3、关注
        Integer followUserId = userRelationDto.getAuthorId();
        if (userRelationDto.getOperation() == 0) {
            // 将对方写入我的关注中
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, followUserId.toString(), System.currentTimeMillis());
            // 将我写入对方的粉丝中
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION + followUserId, userId.toString(), System.currentTimeMillis());
        } else {
            // 取消关注
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + userId, followUserId.toString());
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + followUserId, userId.toString());
        }
        return true;
    }
}
